package yz.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.net.URI;

public class demo7GetFileStatus {
    public static void main(String[] args) throws Exception{
        Configuration entries = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://master:9001"), entries,"root");

        Path path = new Path("/api/apiwolds.txt");
        if (fileSystem.exists(path)){
            FileStatus fileStatus = fileSystem.getFileStatus(path);
            long blockSize = fileStatus.getBlockSize();
            long len = fileStatus.getLen();
            System.out.println("block块长度："+blockSize+"，文件长度："+len);

            //获取block块的位置信息，同时指定任意长度文件所在的block块
            BlockLocation[] fileBlockLocations = fileSystem.getFileBlockLocations(path, 0, len);
            for (BlockLocation fileBlockLocation : fileBlockLocations) {
                //获取Block节点所在哪些节点上
                String[] hosts = fileBlockLocation.getHosts();
                //获取长度信息
                long length = fileBlockLocation.getLength();
                for (String host : hosts) {
                    System.out.println("hosts："+host+"，length："+length);
                }
            }
            //block块长度：134217728，文件长度：24
            //hosts：node2，length：24
            //hosts：node1，length：24

        }

    }
}
